<template>
	<view class="container">
		<view class="example">
			<u--form ref="uForm" :model="user" labelWidth="80px">
				<u-form-item label="关系" prop="relation" required style="margin:10px 0;">
					<view class="flex align-center" style="width: 100%;height:36px;padding-left:10px;color: #333;"
						@click="chooseMenu">{{user.relationName}}</view>
				</u-form-item>
				<u-form-item label="证件类型">
					<view class="flex justify-end align-center" style="width: 100%;">
						<picker @change="cardTypePickerChange($event)" :value="numCardType" :range="nationCardType">
							<view class="picker">
								{{ numCardType > -1 ? nationCardType[numCardType] : "请选择" }}
							</view>
						</picker>
						<text style="margin-left: 20rpx;" class="lg text-gray cuIcon-right"></text>
					</view>
				</u-form-item>
				<u-form-item label="证件号码" prop="idNum" :required="user.relation != '3'?true:false">
					<u-input v-model="user.idNum" placeholder="请输入证件号码" />
					<img @click="openCamera" src="@/static/images/相机.png" style="width: 40rpx;"></img>
				</u-form-item>
				<u-form-item label="姓名" prop="name" required>
					<u-input v-model="user.name" placeholder="请输入姓名" />
				</u-form-item>
				<u-form-item label="性别" prop="sex" required>
					<u-radio-group v-model="user.sex">
						<u-radio v-for="(item, index) in sexs" :key="index" :name="item.value"
							style="margin-right: 20rpx;">
							{{item.text}}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="民族">
					<view class="flex justify-end align-center" style="width: 100%;">
						<picker @change="pickerChange($event)" :value="num" :range="nation">
							<view class="picker">
								{{ num > -1 ? nation[num] : "请选择" }}
							</view>
						</picker>
						<text style="margin-left: 20rpx;" class="lg text-gray cuIcon-right"></text>
					</view>
				</u-form-item>
				<u-form-item label="地址" prop="region" required>
					<view class="flex justify-end align-center" style="position: relative; width: 100%;">
						<view style="width: 100%;height: 100%; position: absolute;left: 0;top: 0;z-index: 998;"
							@click="openPicker"></view>
						<u-input inputAlign="right" v-model="user.region" placeholder="请选择地址" />
						<text style="margin-left: 20rpx;" class="lg text-gray cuIcon-right"></text>
					</view>
				</u-form-item>
				<u-form-item label="详细地址" prop="address" required>
					<u-input v-model="user.address" placeholder="请输入详细地址,精确到门牌号,如XX街道XX区X楼X号" />
				</u-form-item>
				<u-form-item label="手机号" prop="mobile" required style="margin:10px 0;">
					<u-input v-model="user.mobile" placeholder="请输入手机号码" />
				</u-form-item>
			</u--form>
			<u-button type="primary" style="width:90%;margin-top: 50rpx;" throttleTime="2000"
				@click.native="submitButton">完成申领</u-button>
		</view>
		<show-action-sheet :tips="showActionSheet.tips" :itemList="showActionSheet.itemList"
			:show="showActionSheet.show" :maskClosable="showActionSheet.maskClosable"
			:isCancel="showActionSheet.isCancel" @chooseCancel="chooseCancel"
			@activetab='activetab'></show-action-sheet>

		<u-loading-page :loading="isLoading" font-size="14" bg-color="rgba(0,0,0,0.7)"></u-loading-page>
		<!-- 省市县三级联动 -->
		<lotus-address ref="lotus" v-on:choseVal="choseValue" :lotusAddressData="lotusAddressData"></lotus-address>
	</view>
</template>

<script>
	import showActionSheet from '@/components/show-action-sheet/index.vue'
	import lotusAddress from "@/components/Winglau14-lotusAddress/Winglau14-lotusAddress.vue";
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools'
	import {
		getDictType
	} from '@/api/system/public'
	import {
		patientBase,
		getInfoMatch
	} from '@/api/card/index.js'
	import {
		checkDate,
		checkProv,
		checkParity,
		idCard,
		checkPhone,
		vueDebounce
	} from "@/utils/common.js"
	import {
		getConfigKey
	} from "@/api/home/home.js";
	import {
		EventBus
	} from "@/utils/event-bus.js"
	export default {
		components: {
			showActionSheet,
			lotusAddress
		},
		data() {
			return {
				numCardType: 0,
				nationCardType: [
					"身份证号",
					"永久居住证",
				],
				num: 0, //民族index
				nation: [
					"汉族",
					"蒙古族",
					"回族",
					"藏族",
					"维吾尔族",
					"苗族",
					"彝族",
					"壮族",
					"布依族",
					"朝鲜族",
					"满族侗族",
					"瑶族",
					"白族",
					"土家族",
					"哈尼族",
					"哈萨克族",
					"傣族",
					"黎族",
					"僳僳族",
					"佤族",
					"畲族",
					"高山族",
					"拉祜族",
					"水族",
					" 东乡族",
					"纳西族",
					"景颇族",
					"柯尔克孜族",
					"土族",
					"达斡尔族",
					"仫佬族",
					"羌族",
					"布朗族",
					"撒拉族",
					"毛南族",
					"仡佬族",
					"锡伯族",
					"阿昌族",
					"普米族",
					"塔吉克族",
					"怒族",
					"乌孜别克族",
					"俄罗斯族",
					"鄂温克族",
					"德昂族",
					"保安族",
					"裕固族",
					"京族",
					"塔塔尔族",
					"独龙族",
					"鄂伦春族",
					"赫哲族",
					"门巴族",
					"珞巴族",
					"基诺族",
				],
				showActionSheet: {
					show: false,
					maskClosable: true,
					tips: "本次是谁看病？",
					itemList: [],
					color: "#9a9a9a",
					size: 26,
					isCancel: true
				},
				user: {
					relation: "",
					name: "",
					mobile: "",
					sex: "",
					idNum: "",
					nation: "汉族",
					address: "",
					relationName: '请选择关系',
					region: '',
				},
				sexs: [{
					text: '男',
					value: "1"
				}, {
					text: '女',
					value: "2"
				}],
				rules: {
					relation: [{
						required: true,
						message: '关系不能为空',
						trigger: ['change'],
					}],
					idNum: [{
							required: true,
							message: '请输入证件号',
							trigger: ['blur', 'change'],
						},
						{
							// 自定义验证函数
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								var checkID = (value) => {
									if (checkDate(value)) {
										if (checkProv(value.substring(0, 2))) {
											if (checkParity(value)) {
												return true;
											} else {
												return false;
											}
											return true;
										} else {
											return false
										}
									} else {
										return false
									}
								}
								if (checkID(value)) {
									this.autoInputInfo(value)
								}
								return checkID(value);
							},
							message: '身份证不正确',
							// 触发器可以同时用blur和change
							trigger: ['blur', 'change'],
						}
					],
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return checkPhone(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['blur', 'change'],
						}
					],
					name: [{
						required: true,
						message: '姓名不能为空',
						trigger: ['change', 'blur'],
					}],
					region: [{
						required: true,
						message: '地址不能为空',
						trigger: ['change', 'blur'],
					}],
					address: [{
						required: true,
						message: '详细地址不能为空',
						trigger: ['change', 'blur'],
					}],
					sex: [{
						required: true,
						message: '性别不能为空',
						trigger: ['change', 'blur'],
					}],
				},
				isLoading: false,
				lotusAddressData: {
					visible: false,
					provinceName: '',
					cityName: '',
					townName: '',
				},
			}
		},
		onLoad(options) {
			// this.getUser()
			this.getDefaultAddress()
			this.getRelation()
			this.jumpType = options.jumpType
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);

		},
		methods: {
			/* 获取地址默认配置 */
			getDefaultAddress() {
				getConfigKey('default_address').then(res => {
					let addressStr = res.msg || ''
					if (addressStr != '') {
						let addressArry = addressStr.split('，')
						this.lotusAddressData.provinceName = addressArry[0] || '';
						this.lotusAddressData.cityName = addressArry[1] || '';
						this.lotusAddressData.townName = addressArry[2] || '';
						// this.$refs.lotus.chosedVal2('河南省','郑州市','中原区')
						this.user.region =
							`${this.lotusAddressData.provinceName} ${this.lotusAddressData.cityName} ${this.lotusAddressData.townName}`; //region为已选的省市区的值

					} else {
						this.lotusAddressData.provinceName = '';
						this.lotusAddressData.cityName = '';
						this.lotusAddressData.townName = '';
						this.user.region = ''
					}

				});
			},
			//打开picker
			openPicker() {
				this.lotusAddressData.visible = true;
				// this.lotusAddressData.provinceName = '河南省';
				// this.lotusAddressData.cityName = '郑州市';
				// this.lotusAddressData.townName = '中原区';
			},
			//回传已选的省市区的值
			choseValue(res) {
				//res数据源包括已选省市区与省市区code
				this.lotusAddressData.visible = res.visible; //visible为显示与关闭组件标识true显示false隐藏
				//res.isChose = 1省市区已选 res.isChose = 0;未选
				if (res.isChose) {
					this.lotusAddressData.provinceName = res.province; //省
					this.lotusAddressData.cityName = res.city; //市
					this.lotusAddressData.townName = res.town; //区
					this.user.region = `${res.province} ${res.city} ${res.town}`; //region为已选的省市区的值
				}
			},
			pickerChange(e) {
				this.num = e.detail.value;
				this.user.nation = this.nation[this.num]
			},
			cardTypePickerChange(e) {
				this.numCardType = e.detail.value;

				if (e.detail.value == 0) { //身份证号
					this.rules.idNum = [{
							required: true,
							message: '请输入证件号',
							trigger: ['blur', 'change'],
						},
						{
							// 自定义验证函数
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								var checkID = (value) => {
									if (checkDate(value)) {
										if (checkProv(value.substring(0, 2))) {
											if (checkParity(value)) {
												return true;
											} else {
												return false;
											}
											return true;
										} else {
											return false
										}
									} else {
										return false
									}
								}
								if (checkID(value)) {
									this.autoInputInfo(value)
								}
								return checkID(value);
							},
							message: '身份证不正确',
							// 触发器可以同时用blur和change
							trigger: ['blur', 'change'],
						}
					]


				}
				if (e.detail.value == 1) { //永久居住证
					this.rules.idNum = [{
						required: true,
						message: '请输入证件号',
						trigger: ['blur', 'change'],
					}]
				}

			},
			openCamera() {
				return this.$modal.showToast('模块建设中')

				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['camera', 'album'], //这要注意，camera掉拍照，album是打开手机相册
					success: (res) => {
						if (res.tempFiles[0].size <= 10 * 1024 * 1024) {
							// 图片转为base64
							pathToBase64(res.tempFilePaths[0]).then(path => {
								// this.getImageUrl(path);
								console.log(path, 789)
							})
						} else {
							this.errorToast = "请上传小于10MB的图片";
						}
					}
				});
			},
			getRelation() {
				getDictType({
					dictType: 'sys_relation'
				}).then(res => {
					let arr = []
					res.rows.forEach(item => {
						arr.push({
							value: item.dictValue,
							text: item.dictLabel
						})
					})
					this.showActionSheet.itemList = arr
				})
			},
			activetab(val) {
				this.user.relation = val.value
				this.user.relationName = val.text
				this.chooseCancel()
				if (this.user.relation == '3') {
					this.rules.idNum = [{
						// 自定义验证函数
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的
							var checkID = (value) => {
								if (checkDate(value)) {
									if (checkProv(value.substring(0, 2))) {
										if (checkParity(value)) {
											return true;
										} else {
											return false;
										}
										return true;
									} else {
										return false
									}
								} else {
									if (value == '') {
										return true;
									} else {
										return false;
									}
								}
							}
							if (checkID(value)) {
								this.autoInputInfo(value)
							}
							return checkID(value);
						},
						message: '身份证不正确',
						// 触发器可以同时用blur和change
						trigger: ['blur', 'change'],
					}]
				} else {
					this.rules.idNum = [{
							required: true,
							message: '请输入证件号',
							trigger: ['blur', 'change'],
						},
						{
							// 自定义验证函数
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								var checkID = (value) => {
									if (checkDate(value)) {
										if (checkProv(value.substring(0, 2))) {
											if (checkParity(value)) {
												return true;
											} else {
												return false;
											}
											return true;
										} else {
											return false
										}
									} else {
										return false
									}
								}
								if (checkID(value)) {
									this.autoInputInfo(value)
								}
								return checkID(value);
							},
							message: '身份证不正确',
							// 触发器可以同时用blur和change
							trigger: ['blur', 'change'],
						}
					]
				}
			},
			change(e) {
				console.log("e:", e);
			},
			// 点击弹窗
			chooseMenu() {
				this.showActionSheet.show = true;
			},
			// 弹窗关闭
			chooseCancel() {
				this.showActionSheet.show = false;
			},
			/* 提交防抖 */
			submitButton() {
				vueDebounce(this.submits, 1000);
			},
			submits() {
				this.$refs.uForm.validate().then(res => {
					this.isLoading = false
					let openid = uni.getStorageSync('openid') || ''
					this.user.openId = openid
					this.user.nickName = this.$store.state.user.name || ''
					this.user.headImg = this.$store.state.user.avatar || ''
					this.user.hospitalCode = JSON.parse(uni.getStorageSync('hospital')).hospitalCode || ''
					this.isLoading = true
					let idNum = ''
					if (this.user.idNum) {
						// 身份证号转大写
						this.user.idNum = this.user.idNum.toUpperCase();
						idNum = this.user.idNum
					} else {
						idNum = this.user.mobile
					}
					getInfoMatch({
						name: this.user.name,
						idNum: idNum
					}).then(ress => {
						// getInfoMatch({
						// 	name: '陈延兵',
						// 	idNum: '18330572130'
						// }).then(ress => {
						if (ress.data && ress.data.patientCard) {
							this.user.cardNum = ress.data.patientCard || ''
							this.user.feeType = ress.data.mediTreatement || ''
							this.user.cardStatu = ress.data.cardType || ''
							this.user.feeBalance = ress.data.cardBalance || ''
							if (this.user.idNum == '') {
								this.user.idNum == ress.data.idNum || ''
							}
						} else {
							if (this.user.relation == '3' && this.user.idNum == '') {
								this.user.cardNum = 'wk' + this.user.mobile
							}
						}

						let obj = {
							address: this.lotusAddressData.provinceName + this.lotusAddressData
								.cityName + this.lotusAddressData.townName + this.user.address
						}
						let params = Object.assign({}, this.user, obj)
						patientBase(params).then(res => {
							this.isLoading = false
							if (res.code == 200) {
								this.$msg("新增成功!")
								EventBus.$emit('CardList', '')
								EventBus.$emit('loadFunction', '')
								EventBus.$emit('loadVisitor', '')
								EventBus.$emit('pay', '')
								EventBus.$emit('report', '')
								uni.navigateBack()
							}
						}).catch(errors => {
							this.isLoading = false
						})
					}).catch(errors => {
						this.isLoading = false
					})
				}).catch(errors => {
					this.isLoading = false
				})
			},
			autoInputInfo(value) {
				if(this.user.idNum){
					this.user.sex = idCard(value, 2) == '男' ? '1' : '2'
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: rgb(245, 245, 245);
		padding: 0;
		margin: 0;
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		overflow: hidden;
		overflow-y: auto;
	}

	.example {}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		line-height: 35px;
		margin-left: 10px;
	}


	.u-form-item {
		margin-bottom: 0px;
		padding: 3px 15px;
		background: #fff;
		border-bottom: 1px solid rgb(245, 245, 245);
	}

	.u-input {
		border: none !important;
		font-size: 14px !important;
		color: #333 !important;
	}

	::v-deep .is-input-border {
		border: none !important;
		font-size: 14px !important;
		color: #333 !important;
	}

	::v-deep .uni-select {
		border: none !important;
		font-size: 14px !important;
		color: #333 !important;
	}

	::v-deep .u-radio-group {
		font-size: 14px !important;
		color: #333 !important;
		padding-left: 10px;
	}

	::v-deep uni-textarea {
		height: 65px;
		font-size: 14px !important;
		padding: 8px 8px 0 0;
		color: #333 !important;
		margin-left: 10px;
	}

	::v-deep .uni-easyinput__placeholder-class {
		font-size: 14px !important;
	}

	::v-deep .uni-forms-item__label {
		color: #000;
		font-weight: 700;
	}
</style>